<?php

namespace app\api\controller\qsy;

use addons\wanlshop\library\WanlPay\WanlPay;
use addons\wanlshop\library\WanlSdk\Common;
use app\admin\model\activity\InformationActivity;
use app\admin\model\activity\ProjectActivity;
use app\admin\model\activity\SubjectActivity;
use app\admin\model\order\Userorder;
use app\admin\model\user\UserLvl;
use app\api\model\wanlshop\RechargeOrder;
use app\api\model\wanlshop\Shop;
use app\common\controller\Api;

use app\common\handler\TimeHandler;
use app\common\helpers\CommonHelper;
use app\common\model\Config;
use app\common\model\MoneyLog;
use app\common\model\VirtualCoinLog;
use think\Cache;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;
use app\admin\model\party\Party as PartyModel;

/**
 * 丘山阅
 */
class Order extends Api
{
    protected $noNeedLogin = ['ticketList'];
    protected $noNeedRight = ['*'];


    /**
     * 提交订单
     *
     * @ApiSummary  (WanlShop 订单接口提交订单)
     * @ApiMethod   (POST)
     *
     * @param string $data 数组
     */
    public function addOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $result = false;
            $params = $this->request->post();
            $recharge_ratio = Config::getRechargeRatio();

            $user_id = $this->auth->id; // 用户ID
            if(!in_array($params['type'],['information','party','project','subject'])){
                $this->error(__('非法提交，类型不存在'));
            }


            $id =  $params['id'];
            $one_day = 0;
            switch ($params['type']){
                case 'information':
                    $info = (new InformationActivity())->where(['id'=>$id,'status'=>1])->find();
                    break;
                case 'party':
                    $info = (new \app\admin\model\party\Party())->where(['id'=>$id,'status'=>1,'is_del'=>'0'])->find();
                    if($params['money'] <= 0){
                        $this->error(__('订单金额必须大于0'));
                    }
                    $info['price'] = $params['money'];
                    break;
                case 'project':
                    $info = (new ProjectActivity())->where(['id'=>$id,'status'=>1])->find();
                    if(!$params['one_day'])  {
                        $this->error(__('请选择场次'));
                    }
                    $one_day = $params['one_day'];
                    break;
                default:
                    $info = (new SubjectActivity())->where(['id'=>$id,'status'=>1])->find();
                    if(!$params['one_day'])  {
                        $this->error(__('请选择场次'));
                    }
                    $one_day = $params['one_day'];
                    break;
            }

            if(!$info){
                $this->error(__('活动已删除或未上架，请返回重新选择'));
            }

            // 数据库事务操作
            Db::startTrans();
            try {
                //获取虚拟币比例

                // 获取店铺ID
                $shop_id = $info['shop_id'];
                // 生成订单
                $order = new \app\api\model\wanlshop\Order;
                $order->type = $params['type'];
                $order->user_id = $user_id;
                $order->shop_id = $shop_id;
                $order->order_no = $shop_id.$user_id;
                if(isset($params['remarks'])){
                    $order->remarks = $params['remarks'];
                }
                // 获取平台优惠劵
                $coupon_id = isset($params['coupon_id']) ? $params['coupon_id'] : 0 ;
                $coupon = model('app\api\model\wanlshop\CouponReceive')
                    ->where(['id' => $coupon_id, 'user_id' => $user_id, 'shop_id' => 0])
                    ->find();
                $order->coupon_id = $coupon ? $coupon['id'] : 0;

                //临时用
                $order->verify_code = mt_rand(1000000000, 9999999999);
                $order->verify_expire_time = $info['end_time'] ? strtotime($info['end_time']) + 86399 : 0;
                // 要补充活动ID
                if($order->save()){
                    // 计算订单价格
                    
//                      $redis = Common::redis();
                        // 1.1.2升级
//                        $sku_key = 'sys_'.$params['type'].'_'.$info['id'];
                        // 1.1.2升级 提交订单判断库存
//                        if($sku['stock'] <= 0){
//                            throw new Exception("商品被抢光了");
//                        }else if($sku['stock'] < $data['number']){
//                            throw new Exception("库存不足");
//                        }
                        // 库存计算方式:porder=下单减库存,payment=付款减库存
//                        if($goods['stock'] == 'porder'){
//                            // 1.1.2升级
//                            if($data['number'] > $redis->llen("{$sku_key}")){
//                                throw new Exception("系统繁忙，请稍后抢购！");
//                            }else{
//                                for ($i = 0; $i < $data['number']; $i ++) {
//                                    $redis->rpop("{$sku_key}");
//                                }
//                                $sku->setDec('stock', $data['number']); // 1.0.3升级
//                            }
//                        }

                    $price = $info['price'];
                    if($one_day != 0){
                       $ticket =  Db::name('qsy_activity_ticket')->field('day,price')->where(['activity_id'=>$id,'type'=>$params['type'],'day'=>$one_day])->find();

                       if($ticket){
                           $price =  $ticket['price'];
                       }
                    }

                    $priceAll = bcmul($price, $params['number'], 2);

                    $goodsList = [
                        'order_id' => $order->id, // 获取自增ID
                        'goods_id' => $info['id'],
                        'shop_id' => $shop_id,
                        'title' => $info['title'],
                        'one_day' => $one_day,
                        'price' => $price, // 原价
                        'image' => $info['cover_img'],
                        'discount_price' => 0, // 优惠金额
                        'actual_payment' => $priceAll, // 1.0.6修复 实际支付，因为要和总价进行计算
                        'number' => $params['number']
                    ];
                    $coupon_price = 0; //优惠券金额
                    $discount_price = 0; // 优惠金额，因为后续版本涉及到活动减免，所以优惠金额要单独拎出来

                    $coupon_after_price = $priceAll;
                    // 如果优惠券存在
                    if($coupon) {
                        // 判断是否可用
                        if($priceAll >= $coupon['limit']){
                            // 优惠金额
                            if($coupon['type'] == 'reduction' || ($coupon['type'] == 'vip' && $coupon['usertype'] == 'reduction')){
                                $coupon_price = $coupon['price'];
                                //总金额 =（订单金额 - 优惠券金额）+ 运费
                                $coupon_after_price = bcadd(bcsub($priceAll, $coupon_price, 2), 0, 2);
                            }
                            // 折扣金额
                            if($coupon['type'] == 'discount' || ($coupon['type'] == 'vip' && $coupon['usertype'] == 'discount')){
                                // 排除异常折扣，还原百分之
                                $discount = $coupon['discount'] > 10 ? bcdiv($coupon['discount'], 100, 2) : bcdiv($coupon['discount'], 10, 2);
                                // 优惠金额 = 订单金额 - 订单金额 * 折扣
                                $coupon_price = bcsub($priceAll, bcmul($priceAll, $discount, 2), 2);
                                $coupon_after_price = bcadd(bcsub($priceAll, $coupon_price, 2), 0, 2);
                            }

                            $discount_price = $coupon_price;

                            $goods_price = bcmul($goodsList['price'], $goodsList['number'], 2);
                            $goods_discount_price = round($coupon_price * ( $goods_price / $priceAll ), 2); // 优惠金额
                            // 1.0.8升级,修复包邮
                            $actual_payment = $coupon['type'] === 'shipping' ? $goods_price : bcsub($goods_price, $goods_discount_price, 2);
                            //优惠价格
                            $goodsList['discount_price'] = $goods_discount_price;
                            // 实际支付 1.0.9升级
                            $goodsList['actual_payment'] = $actual_payment <= 0 ? '0.00' : $actual_payment;
                            
                            // 更新已使用数量
                            model('app\api\model\wanlshop\Coupon')
                                ->where(['id' => $coupon['coupon_id']])
                                ->setInc('usenum');
                            // 修改该优惠券状态 已用
                            $coupon->allowField(true)->save(['state' => 2]);
                        }else{
                            model('app\api\model\wanlshop\Order')->destroy($order->id);
                            throw new Exception('订单金额'.$priceAll.'元，不满'.$coupon['limit'].'元');
                        }
                    }
//                    $lvlInfo = (new UserLvl())->where('id',$this->auth->level)->find();
//                    $member_discount = 0;
//                    $member_discount_price = 0;
//                    if($lvlInfo && $lvlInfo['rebate'] > 0){
//                        $member_discount = $lvlInfo['rebate'];
//                        $member_discount_price =  $priceAll- ($priceAll * $member_discount /10);
//                        $coupon_after_price  = round($coupon_after_price - $member_discount_price,2);
//
//                        $goodsList['discount_price'] = $discount_price+ $member_discount_price;
//                        $goodsList['actual_payment'] = $coupon_after_price <= 0 ? 0.00 : $coupon_after_price;
//
//                    }

                    $lvlInfo = (new UserLvl())->where('id',$this->auth->level)->find();

                    $member_discount = 0;
                    $member_discount_price = 0;
                    if($this->auth->isMember() && $lvlInfo && $lvlInfo['rebate'] > 0){
                        $member_discount = $lvlInfo['rebate'];
                        $coupon_after_price =round($goodsList['actual_payment'] * $member_discount /10,2);
                        $member_discount_price = round(($goodsList['actual_payment']- $coupon_after_price),2);
                        $goodsList['member_discount_price'] = $member_discount_price;
                        $goodsList['actual_payment'] = $coupon_after_price < 0.01 ? '0.00' : $coupon_after_price;
                    }
                    $pay_type = 0;
                    $pay_state = 0;
                    if($coupon_after_price <= 0){     //支付金额小于0 默认微信支付
                        $pay_type = 1;
                        $pay_state = 1;
                        $model_order = model('app\api\model\wanlshop\Order');
                        $model_order->save(['state'  => 8, 'paymenttime' => time()],['id' => $order->id]);
                    }
                    // 生成支付
                    $payList[] = [
                        'pay_type'=>$pay_type,
                        'pay_state'=>$pay_state,
                        'user_id' => $user_id,
                        'shop_id' => $shop_id,
                        'order_id'  => $order->id,
                        'order_no'  => $order->order_no,
                        'pay_no' => $order->order_no,
                        'type' => 'activity', // 1.0.8升级
                        'price'  => $coupon_after_price <= 0 ? 0.00 : $coupon_after_price,
                        'order_price' => $priceAll, // 订单总金额
                        'coupon_price' => $coupon_price,  // 优惠券金额
                        'discount_price' => $discount_price, // 优惠金额
                        'number'  => $params['number'],
                        'member_discount' => $member_discount,  // 会员折扣
                        'member_discount_price' => $member_discount_price,  // 会员折扣金额
                        'recharge_ratio'=>   $recharge_ratio
                    ];
                }else{
                    throw new Exception('网络繁忙，创建订单失败！');
                }
                
                model('app\api\model\wanlshop\OrderGoods')->save($goodsList);
                $result = model('app\api\model\wanlshop\Pay')->saveAll($payList);

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                foreach ($result as &$v){
                    $v['expiretime'] = $v['createtime'] + (15 * 60);
                    $v['virtual_coin'] = round($v['price'] * $recharge_ratio,2);
                    \think\Queue::later(15 * 60, '\addons\wanlshop\job\OrderAutoOper@autoClose', ['order' => $order], 'wanlshop');
                }
                $this->success('返回成功',  ['list' => $result,'token' => self::creatToken()]);
            } else {
                $this->error(__('订单异常，请返回重新下单'));
            }
        } else {
            $this->error(__('非法请求'));
        }
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取订单详情
     */
    public function getOrderInfo()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $id = $this->request->request('id');
        $id ? $id : ($this->error(__('非法请求')));
        $order = model('app\api\model\wanlshop\Order')
            ->where(['id' => $id, 'user_id' => $this->auth->id])
            ->field('id,type,state,verify_code,verify_expire_time,verify_time')
            ->find();
        // 获取订单商品
        $order['goods'] = model('app\api\model\wanlshop\OrderGoods')
            ->where(['order_id'=> $id])
            ->field('id,goods_id,title,image,price,actual_payment,discount_price,number,refund_id,refund_status')
            ->find();

        $order['pay'] = model('app\api\model\wanlshop\Pay')
            ->where(['order_id' => $id, 'type' => 'activity'])
            ->field('id, pay_no,pay_type, number, price, order_price, freight_price, discount_price, actual_payment, recharge_ratio')
            ->find();
        switch ($order['type']){
            case 'information':
                $info = (new InformationActivity())->alias('p')
                    ->field('s.shopname,p.address,p.lng,p.lat,p.phone')
                    ->join('wanlshop_shop s','s.id = p.shop_id','left')
                    ->where(['p.id'=>$order['goods']['goods_id']])->find();
                break;
            case 'party':
                $info = (new PartyModel())->alias('p')
                    ->join('wanlshop_shop s','s.id = p.shop_id','left')
                    ->field('s.shopname,address,lng,lat,phone')
                    ->where('p.id','=',$order['goods']['goods_id'])
                    ->find();
                break;
            case 'project':
                $info = (new ProjectActivity()) ->alias('p')
                    ->field('s.shopname,p.address,p.lng,p.lat,p.phone')
                    ->join('wanlshop_shop s','s.id = p.shop_id','left')
                    ->where(['p.id'=>$order['goods']['goods_id']])->find();
                break;
            default:
                $info = (new SubjectActivity())->alias('p')
                    ->join('wanlshop_shop s','s.id = p.shop_id','left')
                    ->field('s.shopname,p.address,p.lng,p.lat,p.phone')
                    ->where('p.id','=',$order['goods']['goods_id'])
                    ->find();
                break;
        }
        $order['activity'] =$info;
        $order['goods']['virtual_coin']  = $order['goods']['actual_payment'] * $order['pay']['recharge_ratio'] ;
        $this->success('ok',$order);
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 活动选择场次
     */
    public function ticketList(){

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $type = $this->request->post('type');
            $id = $this->request->post('id');

            $page = $this->request->post('page',1);
            $pageSize = $this->request->post('pageSize',10);
            if(!in_array($type,['project','subject'])){
                $this->error(__('非法提交，类型不存在'));
            }
            if($type == 'project') {
                  $model = (new ProjectActivity);
            }else{
                $model = (new SubjectActivity());
            }
            $info = $model->field('id,shop_id,title,price,day_num,start_time,end_time')->where(['id'=>$id,'status'=>'1'])->find();
            if(!$info){
                $this->error(__('该活动商家已删除或已下架，请选择其它活动'));
            }
            $day_num = 0;

            $activity_time = $info['start_time'];
            if(strtotime($activity_time) < time()){
                $activity_time  = date('Y-m-d') ;
            }
            
            if($activity_time && $info['end_time']){
                $day_num= CommonHelper::getTimeDay($activity_time,$info['end_time']);
                $day_num = $day_num+1;
            }

            $data =[];
            $start_time = strtotime( $activity_time);

            $num = ($page * $pageSize) -1;
            if($day_num > 0 && $day_num >= ($num - $pageSize)){
                $time = strtotime(  '+ '.$num . ' day', $start_time);
                $start =  $start_time;
               if($time < strtotime($info['end_time'])){
                   if($page > 1){
                       $start= strtotime( (($page-1)*$pageSize) . ' day', $start_time);
                   }
                   $end =  TimeHandler::getStrtotimeDate($time,'Y-m-d') ;
               }else{
                   if($page > 1){
                       $start =   strtotime( (($page-1)*$pageSize) . ' day', $start_time);
                   }
                   $end = $info['end_time'];
               }

                $start = TimeHandler::getStrtotimeDate($start,'Y-m-d') ;
                $timeArr = CommonHelper::getDays($start,$end);

               $ticketList = Db::name('qsy_activity_ticket')->field('day,price,num')->where(['activity_id'=>$id,'type'=>$type])->select();
               $ticketArr = array_column($ticketList,null,'day');
               $shop = (new Shop())->get($info['shop_id']);

               $lvlInfo = (new UserLvl())->where('id',$this->auth->level)->find();

               foreach ($timeArr  as  $v){
                   $prcie = isset($ticketArr[$v]) ? $ticketArr[$v]['price'] : $info['price'];
                   $member_price = $prcie;
                   if($this->auth->isMember() && $lvlInfo && $lvlInfo['rebate'] > 0){
                       $member_discount = $lvlInfo['rebate'];
                       $member_price =  $member_price * $member_discount /10;
                   }
                   $data[]=[
                       'key'=>$v,
                       'day'=> $v,
                       'price'=>$prcie,
//                       'num' =>isset($ticketArr[$v]) ? $ticketArr[$v]['num'] : $info['day_num'],
                       'member_price'=> $member_price,
                       'week'=> TimeHandler::getWeek($v),
                       'open_hours'=> $shop['open_hours']
                   ];
               }
            }
            $this->success('返回成功', [
                'info'=>$info,
                'list'=>$data
            ]);

        }
        $this->error(__('非法请求'));
    }

    /**
     * 充值记录
     */
    public function rechargeList(){
        $user_id = $this->auth->id; // 用户ID
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $model = (new RechargeOrder)
            ->field('id,orderid,createtime,payamount,(recharge_ratio * amount) as virtual_coin')
            ->where('user_id',$user_id)
            ->where('status','paid')
            ->order('createtime desc')
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);
        $total= $model->total();
        $list =  $model->items();
        $result = array("total" =>$total , "list" => $list);
        $this->success("获取成功",$result);
    }

    /**
     * 使用记录 和  退款记录
     */
    public function moneyRefundUseList(){
        $user_id = $this->auth->id; // 用户ID
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $type = $this->request->param('type');
        $where =[];
        if($type == 'refund'){
            $where['type'] =['in',['refund','groups_refund']];
        }
        if($type == 'use'){
            $where['type'] =['in',['sys','pay','groups']];
        }
        $model = (new VirtualCoinLog)
            ->field('id,money as virtual_coin,createtime,payamount')
            ->where('user_id',$user_id)
//            ->where('memo','like','余额%')
            ->where($where)
            ->order('createtime desc')      
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);
        $total= $model->total();
        $list =  $model->items();
        $result = array("total" =>$total , "list" => $list);
        $this->success("获取成功",$result);
    }

    public function addMemberOrder(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $type = $this->request->post('type','wechat');
            $method = $this->request->post('method','miniapp');
            $code = $this->request->post('code');
            $lvl_id = $this->request->post('lvl_id');

            //获取会员卡信息
            $lvlInfo = UserLvl::get(['id'=>$lvl_id,'status'=>'1']);
            if(!$lvlInfo){
                $this->error('该会员卡不存或已下架，请重新选择');
            }

            if($lvlInfo['price'] <=0){
                $this->error('支付金额不合法');
            }
            //调用支付
            $wanlPay = new WanlPay($type, $method, $code);
            $data = $wanlPay->buyMember($lvlInfo);
            if($data['code'] == 200){
                $this->success($data['msg'], $data['data']);
            }else{
                $this->error($data['msg']);
            }
        }
    }

    
    /**
     * 创建Token
     */
    public function creatToken()
    {
        $code = chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE));
        $key = "WANLSHOP.COM";
        $code = md5($key . substr(md5($code), 8, 10));
        Cache::set('activityOrderToken_'. $this->auth->id, $code, 180);
        return $code;
    }


}
